const router = require('koa-router')()
const path = require('path');
const sqlQuery = require('./db.js');

router.prefix('/exam')


router.get('/', async (ctx, next) => {
  try {
    ctx.body = {
      status: 1,
      message: "测试接口"
    }
  } catch (error) {
    next(error)
  }
})
//登录验证
router.post("/login", async (ctx, next) => {
  try {
    let val = ctx.request.body
    let data = await sqlQuery("select * from exam_userid a,exam_userinfo b where (a.userIDId=? or a.userinfoPhone=?) and a.userIDPassword=? and a.userinfoId=b.userinfoId",
      [val.user, val.user, val.password])
    ctx.body = {
      status: data.length,
      message: data
    }
  } catch (error) {
    next(error)
  }
})
// 查询所有选择题 和 选择题数量
router.get('/choice', async (ctx, next) => {
  try {
    let sql = `select * from choice`;
    let result = await sqlQuery(sql, []);
    sql = `select count(*) count from choice`
    let resultCount = await sqlQuery(sql, []);
    let count = resultCount[0].count
    ctx.body = {
      status: 1,
      message: result,
      count
    }
  } catch (error) {
    next(error)
  }
})

// 存储错题
router.post('/puterrors', async (ctx, next) => {
  try {
    let { uid, errors, grade } = ctx.request.body;
    let sql = `insert into mistakes(errors,grade,uid) values(?,?,?)`;
    let result = await sqlQuery(sql, [errors,grade,uid]);
    ctx.body = {
      status: 1,
      message:result
    }
  } catch (error) {
    next(error)
  }
})

// 获取错题
router.get('/geterrors/:uid', async (ctx, next) => {
  try {
    let { uid } = ctx.params;
    let sql = `select * from mistakes where uid=?`;
    let result = await sqlQuery(sql, [uid]);
    ctx.body = {
      status: 1,
      message:result
    }
  } catch (error) {
    next(error)
  }
})

module.exports = router
